package com.javaclimb.music.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.javaclimb.music.domain.Collect;
import com.javaclimb.music.exection.BizCodeEnum;
import com.javaclimb.music.service.CollectService;
import com.javaclimb.music.utils.PageUtils;
import com.javaclimb.music.utils.R;
import com.javaclimb.music.vo.CollectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 收藏控制类
 */
@RestController
@RequestMapping("/collect")
public class CollectController {

    @Autowired
    private CollectService CollectService;

    /**
     * 添加收藏
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object addCollect(@RequestBody @Valid CollectVo collectVo) {
        List<Collect> list = CollectService.list(new LambdaQueryWrapper<Collect>().eq(Collect::getUserId, collectVo.getUserId()).eq(Collect::getSongId, collectVo.getSongId()));
        if (list.size() != 0) {
            return R.error(BizCodeEnum.Already_Favorite);
        }

        //保存到收藏的对象中
        Collect collect = new Collect();
        BeanUtils.copyProperties(collectVo, collect);
        boolean flag = CollectService.save(collect);
        if (flag) {   //保存成功
            return R.ok();
        }
        return R.error(BizCodeEnum.ADD_ERROR);
    }

    /**
     * 删除收藏
     */
    @GetMapping("/delete")
    public Object deleteCollect(@Valid CollectVo collectVo) {
        boolean remove = CollectService.remove(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUserId, collectVo.getUserId())
                .eq(Collect::getSongId, collectVo.getSongId())
        );
        if (remove) {
            return R.ok();
        } else {
            return R.error(BizCodeEnum.DELETE_ERROR);
        }
    }

    /**
     * 查询所有收藏
     */
    @GetMapping(value = "/allCollect")
    public Object allCollect(@RequestParam Map<String, Object> params) {

        PageUtils pageUtils = CollectService.queryPage(params);
        return R.ok().put("data", pageUtils);
    }

    /**
     * 查询某个用户的收藏列表
     */
    @GetMapping(value = "/collectOfUserId")
    public Object collectOfUserId(Integer userId) {
        List<Collect> list = CollectService.list(new LambdaQueryWrapper<Collect>().eq(Collect::getUserId, userId));
        return R.ok().put("data", list);
    }

}






















